<?php

class DefaultController extends BaseController
{
    public function defaultAction()
    {
        $this->view->assign('title','О проекте');
        $this->view->display('default.default.tpl');
    }
    
    public function dashboardAction()
    {
        $projects = Project::getAll();
        $this->view->assign('projects',$projects);

        $this->view->assign('nav', array('Панель управления проектами' => '/dashboard'));
        $this->view->assign('title','Панель управления проектами');

        $this->view->display('default.dashboard.tpl');
    }
    
    public function planBuildAction()
    {
        using('Framework.System.Ajax');
        $id = intval($_GET['project_id']);
        $project = Project::getById($id);
        if(!$project) {
            AjaxRoute::showData(array('code'=>300,'message'=>'Project with ID '.$id.' not found'));
        }
        $params = array(
            'task' => 'build',
            'state' => Scheduler::PLANED_TASK,
            'project_id' => $project->id,
            'result_path' => realpath( SITE_DIR.'/../builds/'.$project->name.'/' ));
        $task = Scheduler::saveIfNotExists($params);
        
        AjaxRoute::showData(array('code'=>200,'body'=>$task->getState()));
    }
    
    public function cancelBuildAction()
    {
        using('Framework.System.Ajax');
        $id = intval($_GET['project_id']);
        $project = Project::getById($id);
        if(!$project) {
            AjaxRoute::showData(array('code'=>300,'message'=>'Project with ID '.$id.' not found'));
        }
        $task = $project->getCurrentTask();
        if($task->state == Scheduler::START_TASK) {
            $task->state = Scheduler::CANCEL_TASK;
            $task->save();
        } elseif($task->state == Scheduler::PLANED_TASK) {
            $task->delete();
            $task = $project->getCurrentTask();
		}

        AjaxRoute::showData(array('code'=>200,'body'=>$task->getState()));
    }
    
    public function getProjectsStateAction()
    {
        using('Framework.System.Ajax');
        $id = intval($_GET['project_id']);
        $projects = Project::getAll();
        $res = array();
        foreach($projects as $project) {
            $task = $project->getCurrentTask();
            $r = $task->getState();
            $r['pid'] = $project->id;
            $r['state'] = $task->state;
            $res[] = $r;
        }
        
        AjaxRoute::showData(array('code'=>200,'body'=>$res));
    }
}
